﻿
var canvasel = document.getElementById('c');

if ($(window).width() > 480) {
    canvasel.width = 320;
    canvasel.height = 480;
}
else {
    canvasel.width = $(window).width();
    canvasel.height = $(window).height();
}

var w = canvasel.width - 40;
var h = canvasel.height - 40;

var canvas = new fabric.Canvas('c');

canvas.selection = false; //to make sure that there'll be no interaction with multiple objects
canvas.hoverCursor = "pointer";

var position = new Array();

//method generates numbers to be used as coordinates upon the canvas
var generatePosition = function () {

    for (var i = 0; i < 10;) {
        var valid = true;
        
        var coord = { x: fabric.util.getRandomInt(40, w), y: fabric.util.getRandomInt(40, h) };

        if (position.length == 0) {
            position[i] = coord;
            i++;
        }
        else {
            //the loop is used to make sure that no object is placed on another
            for (var key in position) {

                var obj = position[key];
                var x = obj.x;
                var y = obj.y;
                //the radius of each object is 40
                if (coord.x > x - 70 && coord.x < x + 70) {

                    if (coord.y > y - 70 && coord.y < y + 70) {

                        valid = false;
                        break;
                    }
                }
            }
            
            if (valid == true) {
                position[position.length] = coord;
                i++;
            }
        }      
    }
    return position;
}

//will be incremented upon completion of a predetermined number of game rounds, will have effect on generateText method
var difficulty = 0;

//method generates the text which will be displayed on the clickable objects
var generateText = function () {

    var value = new Array();

    if (difficulty == 0) { //numbers

        for (var i = 0; i < 10; i++) {
            value[i] = (i + 1).toString();
        }
        return value;
    }
    if (difficulty == 1) { //letters

        for (var i = 0; i < 10; i++) {
            value[i] = String.fromCharCode(i + 65);
        }
        return value; //will return ASCII characters from 65 - 74 (A-J)
    }
    if (difficulty == 2) { //a mix of both numbers and letters
        var j = 0;
        for (var i = 0; i < 10; i++) {
            if (i % 2 == 0) { //if the remainder is equal to 0 then i is an even number
                value[i] = (j + 1).toString(); // 1 - 5
            }
            else {
                value[i] = String.fromCharCode(j + 65); // A - E
                j++;
            }
        }
        return value;
    }
    if (difficulty == 3) { //random characters from A-Z
        var chars = [];
        var found;
        for (var i = 0; i < 10;) {
            var char = String.fromCharCode(Math.floor(Math.random() * (90 - 65 + 1)) + 65); 
            
            if (chars.length == 0) {
                chars[i] = char;
                i++;
            }
            else {         
                if (chars.indexOf(char) > -1) { //method indexOf returns -1 when there's no match
                    found = true;
                }
                else {
                    found = false;
                }
            }

            if (found == false) {
                chars[i] = char;
                i++;
            }
        }
        return chars.sort();
    }
}

//creates the objects and displays them on canvas
var draw = function () {

    canvas.clear(); //deletes everything on canvas, in this case all groups

    var coords = generatePosition();
    var value = generateText();

    for (var i = 0; i < 10; i++)
    {
        var circle = new fabric.Circle({
            radius: 35, fill: 'black', lockMovementX: true, lockMovementY: true, lockRotation: true,
            lockScalingX: true, lockScalingY: true
        });

        var text = value[i]; //must be type string
        var circleText = new fabric.Text(text, {
            fontSize: 40, fontFamily: 'Verdana', strokeStyle: 'white', strokeWidth: 2
        });

        var group = new fabric.Group([circleText, circle], {
            left: coords[i].x,
            top: coords[i].y,
            index: i //this property will be used to check if the objects have been selected in order
        });
        group.hasControls = false;
        group.hasBorders = false;        
        
        canvas.add(group);
    }
    position.length = 0; //empties the array
    canvas.renderAll();
    canvas.calcOffset(); 
};

var counter = 0;; //variable to increment each time the user presses the right button in order
var error = 0; //records number of user faults for each round
var totalErrorCount = 0;
//var rounds = 0; //incremented for each round completed

canvas.on({'object:selected': validateClick});

function validateClick(e) {
    
    var index = e.target.index;

    if (index == counter) { 
        e.target.set({ fill: 'green' });
        canvas.renderAll();
        counter++;
    }
    if (index == (counter - 1)) {
        //make sure nothing happens when clicking on the same button after a correct entry
    }
    else {
        e.target.set({ fill: 'red' });
        canvas.renderAll();
        error++; totalErrorCount++;
    }

    if (error == 2) { //round failed, redraw canvas

        clearTimeout(timeLimit);
        nextRound();
    }

    if (counter == 10) { //round completed

        clearTimeout(timeLimit);
        difficulty++;

        if (difficulty == 4) { //game end
            showResult();
        }
        else {
            nextRound();
        }
    }
}

var gameStart = null;
var timeLimit = null;

//method is used to set the time limit for each round, when the time limit is reached the canvas will be redrawn
function startTimer () {
    timeLimit = setTimeout(function () {
        nextRound();
    }, 100000);
}
//var gameClock = setInterval(function () { totalGameTime++; }, 1000);

var restartTimer = function () {
    clearTimeout(timeLimit);
    startTimer();
}

//method starts the game
var start = function () {
    
    draw();
    startTimer();
    gameStart = new Date();
}

var nextRound = function () {

    counter = 0;
    error = 0;
    draw();
    restartTimer();
}

var calculateScore = function (time) {

    var score = 240;
    var incorrect = 20;

    if (time > 240) {
        return 0;
    }
    else {
        var userScore = score - (incorrect * totalErrorCount) - (time);
        if (userScore < 0) {
            return 0;
        }
        else {
            return userScore;
        }
    }
}

var totalGameTime;
var myScore;

//method show the users end result
var showResult = function () {
    var gameEnd = new Date();
    totalGameTime = Math.round((gameEnd - gameStart) / 1000);
    myScore = calculateScore(totalGameTime);
    var time = $('<p/>').text("Total tid: " + totalGameTime + " sekunder");
    var faults = $('<p/>').text("Antal fel: " + totalErrorCount);
    var points = $('<p/>').text("Poäng: " + myScore);
    $("#game, #end").toggle();
    $("#result").append(time, faults, points);
}

//this method calls the webmethod saveresult to store the users result
$(function () {
    $("#save").on("click", function () {
        PageMethods.saveResult(totalGameTime, totalErrorCount, myScore);
        $("#save").attr("disabled", "disabled");
        setTimeout(function () {
            window.location = "Main.aspx";
        }, 500);
    });
});

$(function () {
    $("#game").hide();
    $("#instructions").hide();
    $("end").hide();
    $("#start").on("click", function () {
        $("#intro, #game").toggle();
        start();
    });
});

$(function () {
    $("#instr").on("click", function () {
        $("#intro, #instructions").toggle();
    });
});

$(function () {
    $("#return").on("click", function () {
        $("#instructions, #intro").toggle();
    });
});
